#include "glwrapper.hpp"

#include <iostream>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GL/glu.h>
#include <GLFW/glfw3.h>

int carbon::C_GLWrappper::initialize() {
    std::cout << "[TASK] INITIALIZE GL : GLFW" << std::endl;

    if (!glfwInit()) {
        std::cerr << "error: failed to initialize glfw" << std::endl;
        return 11;
    }
    glfwSetErrorCallback(carbon::C_GLWrappper::glfwErrorCallback);
    std::cout << "GLFW VERSION: " << glfwGetVersionString() << std::endl;

    return 0;
}

int carbon::C_GLWrappper::initializeGlew() {
    glewExperimental = true;

    if (GLenum err = glewInit() != GLEW_OK) {
        std::cout << "error: failed to initialize glew: " << glewGetErrorString(err) << std::endl;
        return 12;
    }
    std::cout << "GL VERSION: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GL RENDERER: " << glGetString(GL_RENDERER) << std::endl;

    return 0;
}

int carbon::C_GLWrappper::checkWindow(GLFWwindow* win) {
    if (win == nullptr) {
        std::cerr << "error: assertion WINDOW == NULLPTR failed, window is not initialized" << std::endl;
        glfwDestroyWindow(win);
        return 12;
    }
    return 0;
}
// void carbon::C_GLWrappper::poll_events() { glfwPollEvents(); }

void carbon::C_GLWrappper::terminate() {
    glfwTerminate();
}

void carbon::C_GLWrappper::glfwErrorCallback(int error, const char* description) {
    std::cerr << "GLFW ERROR (" << error << "): " << description << std::endl;
}


void carbon::C_GLWrappper::setGlfwMinmaxVer(int min, int max) {
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, max);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, min);
}
void carbon::C_GLWrappper::setBufferSwapInterval(int interval) {
    glfwSwapInterval(interval);
}

void carbon::C_GLWrappper::enableForwardCompat() {
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
}
void carbon::C_GLWrappper::enableCoreProfile() {
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
}
void carbon::C_GLWrappper::enableMultisampling(int samples) {
    glfwWindowHint(GLFW_SAMPLES, samples);
}

// returns true if glfw is initialized
bool carbon::C_GLWrappper::getGlfwStatus() {
    (void)glfwGetKeyScancode(0);
    return glfwGetError(NULL) != GLFW_NOT_INITIALIZED;
}
bool carbon::C_GLWrappper::getShaderStatus(C_Shader* shader) {
    if (shader == nullptr) {
        return false;
    }
    return true;
}